//
//  LZManageReviewsRestaurantReviewsTableView.m
//  laziz_Merchant
//
//  Created by xbn_iMac on 2016/12/18.
//  Copyright © 2016年 XBN. All rights reserved.
//

#import "LZManageReviewsRestaurantReviewsTableView.h"
#import "UITableView+FDTemplateLayoutCell.h"
#import "LAReviewTableViewCell.h"
#import "LZManageReviewsRestaurantReviewsHeadInfoView.h"
#import "LAReviewHeaderView.h"
#import "LAReviewModel.h"
#import "LZCustomerUserModel.h"
#import "LZReviewsReplyModel.h"

#import "UITableView+LZTableView.h"

#import "IQKeyboardManager.h"

@interface LZManageReviewsRestaurantReviewsTableView ()<UITableViewDelegate,UITableViewDataSource,LAReviewCellDelegate,ReviewHeaderClickDelegate,UITextFieldDelegate>

@property (nonatomic, strong) NSMutableArray *dataArr;
@property (nonatomic, assign) NSInteger selectedHeaderButtonTag;

@property (nonatomic, assign) int page;
@property (nonatomic, assign) int limit;

@property (nonatomic, strong) UITextField *textField;       // 用于占位的
@property (nonatomic, strong) UITextField *textInputReview; // 显示在键盘上的
@property (nonatomic, strong) UITextField *textTemp;        // 记录点击的textField
@property (nonatomic, assign) BOOL isShowKeyBoard;

@end

@implementation LZManageReviewsRestaurantReviewsTableView

-(instancetype)initWithFrame:(CGRect)frame style:(UITableViewStyle)style {
    self = [super initWithFrame:frame style:style];
    if (self) {
        self.backgroundColor = UIColorFromRGB(0xeeeeee, 1);
        self.separatorColor = [UIColor clearColor];
        [self registerCell];
        [self configBaseData];
        self.delegate = self;
        self.dataSource = self;
        [self addFooterRefresh];
        
        [self configReplyTextField];
        
    }
    return self;
}

- (void)checkHaveData {
    if (self.dataArr.count == 0) {
        if (self.subTableViewDelegate && [self.subTableViewDelegate respondsToSelector:@selector(requestDateWithTag:andPrameter:andPage:andLimit:resultSuccess:)]) {
            if (self.mj_footer.state != MJRefreshStateRefreshing) {
                [self.mj_footer beginRefreshing];
            }
        }
    }
    
    if (self.tableHeaderView == nil) {
        [self createHeaderView];
    }
}

#pragma mark - configure Super Refresh method

- (void)upLoadMoreData {
    [self requestListWithType:self.selectedHeaderButtonTag andPage:self.page];
}

- (void)requestListWithType:(NSInteger)type andPage:(int)aPage {

    WS(weakSelf)
    
    [self.subTableViewDelegate requestDateWithTag:2 andPrameter:@{@"type":[NSString stringWithFormat:@"%ld",type]} andPage:aPage andLimit:self.limit resultSuccess:^(NSArray *result,id otherObject) {
        
        [weakSelf.mj_footer endRefreshing];

        if (result && type == self.selectedHeaderButtonTag && aPage == weakSelf.page) {
            if (result) {
                weakSelf.page ++;
                
                if (result.count>0) {
                    [weakSelf.dataArr addObjectsFromArray:result];
                    [weakSelf reloadData];
                }
                else {
                    if (weakSelf.dataArr.count == 0) {
                        [weakSelf setNoDataFooterText];
                    }
                    else {
                        [weakSelf setNoMoreDataFooterText];
                    }
                    [weakSelf.mj_footer endRefreshingWithNoMoreData];
                }
            }
        }
    }];
}

#pragma mark - Private Method

- (void)configBaseData {
    self.page = 1;
    self.limit = 10;
    self.dataArr = [NSMutableArray array];
}

- (void)registerCell {
    [self registerNib:[UINib nibWithNibName:@"LAReviewTableViewCell" bundle:nil] forCellReuseIdentifier:@"cell"];
}

- (void)configReplyTextField {
    
    self.textInputReview = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 40)];
    self.textInputReview.backgroundColor = [UIColor whiteColor];
    self.textInputReview.layer.borderWidth = 0.5;
    self.textInputReview.returnKeyType = UIReturnKeySend;
    self.textInputReview.delegate = self;
    self.textInputReview.layer.borderColor = UIColorFromRGB(0x999999, 1).CGColor;
    
    self.textField = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 40)];
    self.textField.inputAccessoryView = self.textInputReview;
    self.textField.returnKeyType = UIReturnKeySend;
    self.textField.backgroundColor = [UIColor redColor];
    self.textField.hidden = YES;
    self.textField.delegate = self;
    
    
    
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center  addObserver:self selector:@selector(keyboardDidShow)  name:UIKeyboardDidShowNotification  object:nil];
    [center addObserver:self selector:@selector(keyboardDidHide)  name:UIKeyboardWillHideNotification object:nil];

    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    tap.numberOfTapsRequired = 1;
    [self addGestureRecognizer:tap];
}

- (void)tapAction:(UITapGestureRecognizer*)tap {

    [[UIApplication sharedApplication].keyWindow endEditing:YES];
    [[UIApplication sharedApplication].keyWindow endEditing:YES];

}

- (void)keyboardDidShow
{
    [IQKeyboardManager sharedManager].enable = NO;
    if (self.textTemp == self.textField && !self.isShowKeyBoard) {
        if (self.textInputReview.isFirstResponder == YES) {
            return;
        }
        self.isShowKeyBoard = YES;
        [self.textInputReview becomeFirstResponder];
    }
}

- (void)keyboardDidHide
{
    self.isShowKeyBoard = NO;
    [IQKeyboardManager sharedManager].enable = YES;
}

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    self.textTemp = textField;
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (textField == self.textInputReview) {
        [self tapAction:nil];
        
        LAReviewModel *model = self.dataArr[self.textField.tag];
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:self.textField.tag];
        
        if (self.reviewTableDelegate && [self.reviewTableDelegate respondsToSelector:@selector(requestAddReplyWithReviewsUserId:andCommentId:andReplies:ResultSuccess:)]) {
            
            WS(weakSelf)
            [self.reviewTableDelegate requestAddReplyWithReviewsUserId:model.customerUser.userId andCommentId:model.commentId andReplies:textField.text ResultSuccess:^(id result) {
                if (result != nil) {
                    if (model.replies == nil) {
                        model.replies = [NSMutableArray array];
                    }
                    [model.replies addObject:result];
                    [weakSelf reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
                }
            }];
           
        }
        DLog(@"发送发送发送");
    }
    return YES;
}

/**
 创建headerView
 */
-(void)createHeaderView {
    
    UIView *headerView = [[UIView alloc] init];
    
    LZManageReviewsRestaurantReviewsHeadInfoView *infoView = [[LZManageReviewsRestaurantReviewsHeadInfoView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 67)];
    infoView.model = nil;
    [headerView addSubview:infoView];
    
    
    LAReviewHeaderView *reviewTypeView = [[LAReviewHeaderView alloc] init];
    reviewTypeView.frame = CGRectMake(0, CGRectGetHeight(infoView.bounds), [reviewTypeView intrinsicContentSize].width, [reviewTypeView intrinsicContentSize].height);
    reviewTypeView.delegate = self;
    [headerView addSubview:reviewTypeView];
    
    
    headerView.frame = CGRectMake(0, 0, SCREEN_WIDTH, CGRectGetHeight(infoView.bounds)+CGRectGetHeight(reviewTypeView.bounds));
    
    self.tableHeaderView = headerView;
    
    if (self.reviewTableDelegate && [self.reviewTableDelegate respondsToSelector:@selector(requestCommentCountResultSuccess:)]) {
        [self.reviewTableDelegate requestCommentCountResultSuccess:^(id result) {
            infoView.model = result;
            reviewTypeView.model = result;
        }];
    }
}

#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataArr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    LAReviewTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [self configureCell:cell atIndexPath:indexPath];
    
    return cell;
}

- (void)configureCell:(LAReviewTableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath {
    cell.fd_enforceFrameLayout = NO; // Enable to use "-sizeThatFits:"
    
    cell.indexPath = indexPath;
    cell.textField = self.textField;
    WS(weakSelf)
    cell.isShowKeyBoardStatus = ^BOOL(){
        return weakSelf.isShowKeyBoard;
    };
    
    cell.delegate = self;
    cell.reviewType = ReviewType_Restaurants;
    cell.headImageType = HeadImageType_User;
    
    cell.entity = self.dataArr[indexPath.section];
}

#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    LAReviewModel *model = self.dataArr[indexPath.section];
    
    float height = [tableView fd_heightForCellWithIdentifier:@"cell" cacheByIndexPath:indexPath configuration:^(LAReviewTableViewCell *cell) {
        
        [cell getReviewLabel].numberOfLines = model.labReviewNumberOfLine;
        
        [self configureCell:cell atIndexPath:indexPath];
    }];
    
    return height;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return 10;
    }
    return 0.01;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.01;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

-(void)refreshCellHeight:(NSIndexPath *)indexPath {
    [self reloadData];
}

- (void)deleteReplyWithIndex:(NSIndexPath *)indexPath {
    if (self.reviewTableDelegate && [self.reviewTableDelegate respondsToSelector:@selector(requestDeleteWithReplyReplyId:ResultSuccess:)]) {
        
        LAReviewModel *model = self.dataArr[indexPath.section];
        LZReviewsReplyModel *replyModel = model.replies[0];
        
        WS(weakSelf)
        [self.reviewTableDelegate requestDeleteWithReplyReplyId:replyModel.replyId ResultSuccess:^(id result) {
            [model.replies removeAllObjects];
            model.replies = nil;
            [weakSelf reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
        }];
    }
}

#pragma mark - ReviewHeaderClickDelegate

- (void)clickButton:(UIControl *)button {
    self.selectedHeaderButtonTag = button.tag;
    [self.mj_footer endRefreshing];
    [self.dataArr removeAllObjects];
    [self reloadData];
    
    self.page = 1;
    self.limit = 10;
    
    [self checkHaveData];
}

@end
